package com.ndp.fb.rdb.mongo.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ndp.fb.rdb.model.GeoLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.mongo.api.TargetingService;
import com.ndp.fb.rdb.model.AdGeolocation;
@Service
public class TargetingServiceImpl implements TargetingService {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
    private DB adResourceMongoDBClient;


    @Override
    public List<GeoLocation> getAllCountry() {
        DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_ADGEOLOCATION);
        DBObject dbObjectKey = new BasicDBObject("type","country");
        DBCursor cursor = dbCollection.find(dbObjectKey);
        if (cursor == null) {
            return null;
        }
        List<GeoLocation> result = new ArrayList<>();
        DBObject dbObject = null;
        while (cursor.hasNext()) {
            dbObject = cursor.next();
            dbObject.removeField("_id");
            dbObject.put("countryCode", dbObject.get("country_code"));
            dbObject.put("enUSname", dbObject.get("en_US_name"));
            dbObject.put("zhCNname",dbObject.get("zh_CN_name"));
            dbObject.put("supportsCity", dbObject.get("supports_city"));
            dbObject.put("timezone", dbObject.get("timezone"));
            result.add(JSONObject.parseObject(JSON.toJSONString(dbObject), GeoLocation.class));
        }
        return result;
    }

    @Override
	public JSONObject getCountry(String country_code,String lan) {
		DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_ADGEOLOCATION);
        DBObject dbObject = dbCollection.findOne(new BasicDBObject("type", "country").append("country_code", country_code),
				new BasicDBObject("key", 1).append("type", 1).append("country_code", 1).append("supports_region", 1).append("supports_city", 1)
				.append(lan+"_name", 1));
        if (dbObject == null) {
            return null;
        }
        dbObject.removeField("_id");
        return JSONObject.parseObject(JSONObject.toJSONString(dbObject), JSONObject.class);
	}

	@Override
	public JSONObject getLocale(Integer key,String lan) {
		DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_LOCALES);
        DBObject dbObject = dbCollection.findOne(new BasicDBObject("key", key),new BasicDBObject("key", 1).append(lan, 1));
        if (dbObject == null) {
            return null;
        }
        dbObject.removeField("_id");
        return JSONObject.parseObject(JSONObject.toJSONString(dbObject), JSONObject.class);
	}

	@Override
	public JSONObject getUserDevice(String name, String lan) {
		DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_ADTARGETINGCATEGORY);
        DBObject dbObject = dbCollection.findOne(new BasicDBObject("name", name),new BasicDBObject("type", 1).append(lan, 1).append("audience_size", 1).append("name", 1).append("platform", 1));
        if (dbObject == null) {
            return null;
        }
        dbObject.removeField("_id");
        return JSONObject.parseObject(JSONObject.toJSONString(dbObject), JSONObject.class);
	}

	@Override
	public List<AdGeolocation> getCountryByNameCode(String nameCode, String lan) {
		DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_ADGEOLOCATION);
		DBCursor cursor = dbCollection.find(new BasicDBObject("type", "country").append("$or", new Object[]{new BasicDBObject("country_code",
				new BasicDBObject("$regex", nameCode).append("$options", "i")),new BasicDBObject(lan+"_name",new BasicDBObject("$regex", nameCode).append("$options", "i") )}),
				new BasicDBObject("key", 1).append("type", 1).append("country_code", 1).append("supports_region", 1).append("supports_city", 1)
				.append(lan+"_name", 1));
		List<AdGeolocation> result = new ArrayList<>();
		try {
            DBObject dbObject = null;
            while (cursor.hasNext()) {
                dbObject = cursor.next();
                dbObject.removeField("_id");
                dbObject.put("countryCode", dbObject.get("country_code"));
                dbObject.put("name", dbObject.get(lan+"_name"));
                dbObject.put("supportsRegion", dbObject.get("supports_region"));
                dbObject.put("supportsCity", dbObject.get("supports_city"));
                result.add(JSONObject.parseObject(JSON.toJSONString(dbObject), AdGeolocation.class));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            cursor.close();
        }
		
		return result;
	}

	@Override
	public List<JSONObject> getTargetingBrowse(String lan) {
		DBCollection dbCollection = adResourceMongoDBClient.getCollection(MongoConstants.TABLE_NAME_ADTARGETINGBROWSE);
        DBObject dbObject = dbCollection.findOne(new BasicDBObject("lan", lan));
        if (dbObject == null) {
            return null;
        }
        return JSONObject.parseArray(JSONObject.toJSONString(dbObject.get("sub")), JSONObject.class);
	}
}
